//
//  SecurityGuardRecordViewController.m
//  PropertyManager
//
//  Created by TNG on 2018/8/4.
//  Copyright © 2018年 Tng. All rights reserved.
//

#import "SecurityGuardRecordViewController.h"

@interface SecurityGuardRecordViewController () <UICollectionViewDataSource,UICollectionViewDelegate,UITableViewDelegate,UITableViewDataSource>

@property (strong, nonatomic) UIButton * leftBtn;
@property (strong, nonatomic) UILabel * titleLabe;
@property (strong, nonatomic) UIButton * rightBtn;
@property (strong, nonatomic) UIScrollView * sc;
@property (strong, nonatomic) NSMutableArray * weekArr;
@property (strong, nonatomic) NSMutableArray * dayArr;
@property (strong, nonatomic) UICollectionView * collectionView;
@property (strong, nonatomic) NSMutableArray * weekDayArr;
@property (strong, nonatomic) UITableView * tableview;
@property (nonatomic,assign) int page;
@property (nonatomic,assign) BOOL isHeadFresh;
@property (strong, nonatomic) NSMutableArray * dataArr;

@property (nonatomic, strong) UIButton * reSetBtn;
@property (nonatomic, strong) UIButton * searchBtn;
@property (nonatomic, strong) UIButton * startDataBtn;
@property (nonatomic, strong) UIButton * endDataBtn;
@property (nonatomic, strong) UILabel  * detailLabel;

@property (nonatomic,copy) NSString * startTime;
@property (nonatomic,copy) NSString * startTimeStr;
@property (nonatomic,copy) NSString * endTime;
@property (nonatomic,copy) NSString * endTimeStr;

@end

@implementation SecurityGuardRecordViewController

static NSString * SecurityGuardRecordCollectionViewCellID = @"SecurityGuardRecordCollectionViewCell";
static NSString * SecurityGuardRecordTableViewCellID = @"SecurityGuardRecordTableViewCell";

- (void)viewDidLoad {
    [super viewDidLoad];
    self.page = 1;
    self.title = @"巡检记录";
//    [self.view addSubview:self.leftBtn];
//    [self.view addSubview:self.titleLabe];
//    [self.view addSubview:self.rightBtn];
//    NSDate * date = [NSDate date];
//    UIImageView *leftImg=[[UIImageView alloc] initWithFrame:CGRectMake(self.leftBtn.frame.size.width/2-5, (self.leftBtn.frame.size.height-15)/2, 10, 15)];
//    leftImg.image=[UIImage imageNamed:@"leftarr.png"];
//    [self.leftBtn addSubview:leftImg];
//
//    UIImageView * rightImg=[[UIImageView alloc] initWithFrame:CGRectMake(self.rightBtn.frame.size.width/2-5, (self.rightBtn.frame.size.height-15)/2, 10, 15)];
//    rightImg.image=[UIImage imageNamed:@"rightarr"];
//    [self.rightBtn addSubview:rightImg];
//
//    self.titleLabe.text = [NSString stringWithFormat:@"%li年%li月",[CalendarDate year:date],[CalendarDate month:date]];

//    [self addDay];
    
//    for (NSInteger i = self.weekArr.count - 1; i>=0; i--) {
//        SecurityGuardWeekDayModel * model = [[SecurityGuardWeekDayModel alloc] init];
//        model.week = [self.weekArr objectAtIndex:i];
//        model.day = [self.dayArr objectAtIndex:i];
//        if (i==0) {
//            model.isSelect = YES;
//        }
//        [self.weekDayArr addObject:model];
//    }
    
//    [self.view addSubview:self.collectionView];
    [self.view addSubview:self.startDataBtn];
    [self.view addSubview:self.detailLabel];
    [self.view addSubview:self.endDataBtn];
    [self.view addSubview:self.reSetBtn];
    [self.view addSubview:self.searchBtn];
    [self creatTableview];
    [self registCell];
    [self RequestData];
}

-(UIButton *)startDataBtn
{
    if (_startDataBtn == nil) {
        UIButton * btn = [[UIButton alloc] initWithFrame:CGRectMake(0, kStatusAndNavBarH, WIDTH/2 - 70, 44)];
        btn.titleLabel.font = font(14);
        [btn setTitle:@"开始年月日" forState:UIControlStateNormal];
        [btn setTitleColor:SFM153 forState:UIControlStateNormal];;
        [btn addTarget:self action:@selector(startBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        _startDataBtn = btn;
    }
    return _startDataBtn;
}

#pragma mark - 点击开始日期
-(void)startBtnClick:(UIButton *)btn
{
    WeakSelf;
    [[DataPickerView shareView] showView];
    [DataPickerView shareView].sendChooseDateBlock = ^(NSDate * _Nonnull date) {
        NSDateFormatter *dateFormmater = [[NSDateFormatter alloc]init];
        [dateFormmater setDateFormat:@"yyyy年MM月dd日"];
        NSString * resultString = [dateFormmater stringFromDate:date];
        weakSelf.startTimeStr = resultString;
        [dateFormmater setDateFormat:@"yyyy-MM-dd"];
        
        NSString * end = [dateFormmater stringFromDate:date];
        weakSelf.startTime = end;
        
        [weakSelf.startDataBtn setTitle:resultString forState:UIControlStateNormal];
        [weakSelf.startDataBtn setTitleColor:SFM51 forState:UIControlStateNormal];
    };
}

-(UILabel *)detailLabel
{
    if (_detailLabel == nil) {
        _detailLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.startDataBtn.frame), kStatusAndNavBarH, 20, 44)];
        _detailLabel.text = @"至";
        _detailLabel.font = font(14);
        _detailLabel.textColor = [UIColor redColor];
        _detailLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _detailLabel;
}

-(UIButton *)endDataBtn
{
    if (_endDataBtn == nil) {
        _endDataBtn = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.detailLabel.frame), kStatusAndNavBarH, WIDTH/2 - 70, 44)];
        _endDataBtn.titleLabel.font = font(14);
        [_endDataBtn setTitle:@"结束年月日" forState:UIControlStateNormal];
        [_endDataBtn setTitleColor:SFM153 forState:UIControlStateNormal];;
        [_endDataBtn addTarget:self action:@selector(endBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _endDataBtn;
}

#pragma mark - 结束年月日
-(void)endBtnClick:(UIButton *)btn
{
    WeakSelf;
    [[DataPickerView shareView] showView];
    [DataPickerView shareView].sendChooseDateBlock = ^(NSDate * _Nonnull date) {
        NSDateFormatter *dateFormmater = [[NSDateFormatter alloc]init];
        [dateFormmater setDateFormat:@"yyyy年MM月dd日"];
        NSString * resultString = [dateFormmater stringFromDate:date];
        weakSelf.endTimeStr = resultString;
        [dateFormmater setDateFormat:@"yyyy-MM-dd"];
        
        NSString * end = [dateFormmater stringFromDate:date];
        weakSelf.endTime = end;
        
        [weakSelf.endDataBtn setTitle:resultString forState:UIControlStateNormal];
        [weakSelf.endDataBtn setTitleColor:SFM51 forState:UIControlStateNormal];
    };
}

-(UIButton *)reSetBtn
{
    if (_reSetBtn == nil) {
        _reSetBtn = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.endDataBtn.frame), kStatusAndNavBarH, 60, 44)];
        _reSetBtn.titleLabel.font = font(14);
        [_reSetBtn setTitle:@"重置" forState:UIControlStateNormal];
        [_reSetBtn setTitleColor:SFM153 forState:UIControlStateNormal];;
        [_reSetBtn addTarget:self action:@selector(reSetBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _reSetBtn;
}

#pragma mark -  重置
-(void)reSetBtnClick:(UIButton *)btn
{
    self.startTime = nil;
    self.startTimeStr = nil;
    self.endTime = nil;
    self.endTimeStr = nil;
    [self.startDataBtn setTitle:@"开始年月日" forState:UIControlStateNormal];
    [self.endDataBtn setTitle:@"结束年月日" forState:UIControlStateNormal];
    self.isHeadFresh = YES;
    self.page = 1;
    [self RequestData];
}

-(UIButton *)searchBtn
{
    if (_searchBtn == nil) {
        _searchBtn = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.reSetBtn.frame), kStatusAndNavBarH, 60, 44)];
        _searchBtn.titleLabel.font = font(14);
        [_searchBtn setTitle:@"搜素" forState:UIControlStateNormal];
        [_searchBtn setTitleColor:SFMBlueColor forState:UIControlStateNormal];;
        [_searchBtn addTarget:self action:@selector(searchBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _searchBtn;
}

-(void)searchBtnClick:(UIButton *)btn
{
    self.isHeadFresh = YES;
    self.page = 1;
    [self RequestData];
}

-(NSMutableArray *)dataArr
{
    if (_dataArr == nil) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

#pragma mark - 请求数据
-(void)RequestData
{
    WeakSelf;
    NSString * urlStr = [NSString stringWithFormat:@"/rest/gbInspectionSecurityController/getList?pageno=%d&pagesize=10&pkWorkid=%@",self.page,self.companyName];
    [[HTTPClient shareClient] requestWithPath:urlStr AndReturnBlock:^(NSDictionary *dic) {
        if (weakSelf.isHeadFresh) {
            [weakSelf.dataArr removeAllObjects];
        }
        NSArray * dataArr = dic[@"data"][@"list"];
        for (NSDictionary * dics in dataArr) {
            SecurutyGuardRecordModel * model = [SecurutyGuardRecordModel modelWithDic:dics];
            [weakSelf.dataArr addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.tableview reloadData];
        });
    } AndFailMessage:^(NSString *message, NSString *errorCode) {
        [SVProgressHUD ShowErrorMessage:message];
    }];
}

-(UILabel *)titleLabe
{
    if (_titleLabe == nil) {
        _titleLabe = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH/2 - 35, kStatusAndNavBarH + 7, 70, 20)];
        _titleLabe.font = font(12);
        _titleLabe.textColor = SFM51;
        _titleLabe.textAlignment = NSTextAlignmentCenter;
    }
    return _titleLabe;
}

-(UIButton *)leftBtn
{
    if (_leftBtn == nil) {
        _leftBtn = [[UIButton alloc] initWithFrame:CGRectMake(WIDTH/2 - 75, kStatusAndNavBarH + 7, 40, 20)];
        [_leftBtn addTarget:self action:@selector(leftBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _leftBtn;
}

-(UIButton *)rightBtn
{
    if (_rightBtn == nil) {
        _rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(WIDTH/2 + 35, kStatusAndNavBarH + 7, 40, 20)];
        [_rightBtn addTarget:self action:@selector(rightBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightBtn;
}

-(void)leftBtnClick:(UIButton *)btn{
    
}

-(void)rightBtnClick:(UIButton *)btn
{
    
}

-(NSMutableArray *)weekDayArr
{
    if (_weekDayArr == nil) {
        _weekDayArr = [NSMutableArray array];
    }
    return _weekDayArr;
}

-(NSMutableArray *)weekArr
{
    if (_weekArr == nil) {
        _weekArr = [NSMutableArray array];
    }
    return _weekArr;
}

-(NSMutableArray *)dayArr
{
    if (_dayArr == nil) {
        _dayArr = [NSMutableArray array];
    }
    return _dayArr;
}

-(void)addDay{
    for (int i = 0; i<14; i++) {
        if (i==0) {
            NSDate * date = [NSDate date];//当前时间
            NSInteger day = [CalendarDate day:date];
            [self.dayArr addObject:[NSString stringWithFormat:@"%ld",(long)day]];
            NSString * week = [NSString judgeTodayWeek:date];
            [self.weekArr addObject:week];
        }else
        {
            NSDate * date = [NSDate date];//当前时间
            NSDate * lastDay = [NSDate dateWithTimeInterval:-24*60*60*i sinceDate:date];//前i天
            NSInteger day = [CalendarDate day:lastDay];
            [self.dayArr addObject:[NSString stringWithFormat:@"%ld",(long)day]];
            NSString * week = [NSString judgeTodayWeek:lastDay];
            [self.weekArr addObject:week];
        }
    }
}

-(BOOL)hidesBottomBarWhenPushed
{
    return YES;
}

-(UICollectionView *)collectionView
{
    if (_collectionView == nil) {
        UICollectionViewFlowLayout * floweLayout =[[UICollectionViewFlowLayout alloc]init];
        floweLayout.itemSize=CGSizeMake(WIDTH/7, 56);
        floweLayout.minimumLineSpacing=0;
        floweLayout.minimumInteritemSpacing=0;
        floweLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        _collectionView=[[UICollectionView alloc]initWithFrame:CGRectMake(0, kStatusAndNavBarH + 34, WIDTH, 80) collectionViewLayout:floweLayout];
        _collectionView.dataSource=self;
        _collectionView.delegate = self;
        _collectionView.bounces = NO;
        _collectionView.pagingEnabled = YES;
        _collectionView.backgroundColor = SFMWhiteColor;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.bounces = NO;
        [_collectionView registerClass:[SecurityGuardRecordCollectionViewCell class] forCellWithReuseIdentifier:SecurityGuardRecordCollectionViewCellID];
    }
    return _collectionView;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.weekDayArr.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    SecurityGuardRecordCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:SecurityGuardRecordCollectionViewCellID forIndexPath:indexPath];
    if (self.weekDayArr.count) {
        SecurityGuardWeekDayModel * model = [self.weekDayArr objectAtIndex:indexPath.row];
        cell.weekLabel.text = model.week;
        cell.dayLabel.text = model.day;
        cell.weekLabel.textColor = model.isSelect?[UIColor whiteColor]:SFM51;
        cell.dayLabel.textColor = model.isSelect?[UIColor whiteColor]:SFM51;
        cell.bgView.backgroundColor = SFMWhiteColor;
        cell.bgView.backgroundColor = model.isSelect ? SFMNavBarColor:SFMWhiteColor;
        [self getCornerRoundWithSelfView:cell.bgView byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(100, 28)];
    }
    return cell;
}

- (CAShapeLayer *)getCornerRoundWithSelfView:(UIView *)originalView byRoundingCorners:(UIRectCorner)corners cornerRadii:(CGSize)size{
    //绘制左上和左下圆角
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:originalView.bounds byRoundingCorners:corners cornerRadii:size];
    
    CAShapeLayer * maskLayer = [[CAShapeLayer alloc]init];
    
    maskLayer.frame = originalView.bounds;
    
    maskLayer.path = maskPath.CGPath;
    
    originalView.layer.mask = maskLayer;
    
    return maskLayer;
    
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    for (SecurityGuardWeekDayModel * model in self.weekDayArr) {
        model.isSelect = NO;
    }
    SecurityGuardWeekDayModel * model1 = [self.weekDayArr objectAtIndex:indexPath.row];
    model1.isSelect = YES;
    [self.collectionView reloadData];
}

-(void)registCell
{
    [self.tableview registerClass:[SecurityGuardRecordTableViewCell class] forCellReuseIdentifier:SecurityGuardRecordTableViewCellID];
}

-(void)creatTableview{
    if (self.tableview == nil) {
//        UITableView * tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.collectionView.frame), WIDTH, HEIGHT - CGRectGetMaxY(self.collectionView.frame) - kHomeLineH) style:UITableViewStyleGrouped];
        UITableView * tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, kStatusAndNavBarH + 44, WIDTH, HEIGHT - kStatusAndNavBarH - kHomeLineH - 44) style:UITableViewStyleGrouped];
        tableview.delegate = self;
        tableview.dataSource = self;
        tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        if (@available(iOS 11.0, *)) {
            tableview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAutomatic;
        }
        self.tableview = tableview;
        [self.view addSubview:self.tableview];
    }
    
    // 下拉刷新
    WeakSelf;
    self.tableview.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.isHeadFresh = YES;
        weakSelf.page = 1;
        [weakSelf RequestData];
        [weakSelf.tableview.mj_header endRefreshing];
    }];
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    self.tableview.mj_header.automaticallyChangeAlpha = YES;
    
    self.tableview.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        // 结束刷新
        weakSelf.isHeadFresh = NO;
        weakSelf.page += 1;
        [weakSelf RequestData];
        [weakSelf.tableview.mj_footer endRefreshing];
    }];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArr.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 140;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView * line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 10)];
    line.backgroundColor = SFM242;
    return line;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SecurityGuardRecordTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:SecurityGuardRecordTableViewCellID];
    if (self.dataArr.count) {
        SecurutyGuardRecordModel * model = [self.dataArr objectAtIndex:indexPath.section];
        [cell sendSecurutyGuardRecordModel:model];
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
